import smtplib
import getpass

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

username = None
password = None

def login(session):
	global username
	global password

	session.ehlo()
	session.starttls()
	session.ehlo

	while True:
	
		if not username: username = raw_input("Enter gmail username: ").strip()
		if not password: password = getpass.getpass()

		try:
			session.login(username, password)
			return
		except smtplib.SMTPAuthenticationError as e:
			print e
			username = password = ""
		except:
			print "Unknown error with gmail"

def sendEmail(sender, recipient, subject, body):
	"Sends an e-mail to the specified recipient."

	SMTP_SERVER = 'smtp.gmail.com'
	SMTP_PORT = 587

	msg = MIMEMultipart()
	msg['From'] =  sender
	msg['To'] = recipient
	msg['Subject'] = subject
	msg.preamble = subject

	msg.attach(MIMEText(body))

	session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

	login(session)

	session.sendmail(sender, recipient, msg.as_string())
	session.quit()
